#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
福特配置器输出格式优化
优化JSON输出格式，使其更清晰、结构化和易于使用
"""

import sys
import os
import json
from datetime import datetime
sys.path.append('.')

from src.car_series import CarSeries
from src.car_object import CarObject
from src.car_extras import CarExtras


class OutputFormatOptimizer:
    """输出格式优化器"""
    
    def __init__(self):
        self.optimization_stats = {}
    
    def optimize_output_file(self, input_file, output_file):
        """
        优化输出文件格式
        
        Args:
            input_file: 原始输出文件路径
            output_file: 优化后的输出文件路径
            
        Returns:
            bool: 是否成功优化
        """
        print(f"📄 优化输出格式: {input_file} -> {output_file}")
        
        try:
            # 读取原始数据
            with open(input_file, 'r', encoding='utf-8') as f:
                raw_data = json.load(f)
            
            # 执行优化
            optimized_data = self.optimize_data_structure(raw_data)
            
            # 保存优化后的数据
            os.makedirs(os.path.dirname(output_file), exist_ok=True)
            
            with open(output_file, 'w', encoding='utf-8') as f:
                json.dump(optimized_data, f, ensure_ascii=False, indent=2)
            
            print(f"✅ 优化完成，保存到: {output_file}")
            
            # 生成统计信息
            self.generate_optimization_stats(raw_data, optimized_data)
            
            return True
            
        except Exception as e:
            print(f"❌ 优化过程中出错: {e}")
            return False
    
    def optimize_data_structure(self, raw_data):
        """
        优化数据结构
        
        Args:
            raw_data: 原始数据
            
        Returns:
            dict: 优化后的数据结构
        """
        optimized = {
            "metadata": self.create_metadata_section(),
            "car_series": self.optimize_car_series_info(raw_data),
            "vehicles": self.optimize_vehicle_list(raw_data.get('car_objects', [])),
            "summary": self.create_summary_section(raw_data)
        }
        
        return optimized
    
    def create_metadata_section(self):
        """创建元数据部分"""
        return {
            "generated_at": datetime.now().isoformat(),
            "version": "2.0",
            "description": "福特汽车配置抓取数据",
            "data_source": "Ford UK Official Website",
            "scraper_version": "Ford NGc2 Scraper v2.0"
        }
    
    def optimize_car_series_info(self, raw_data):
        """优化车系信息"""
        return {
            "name": raw_data.get('car_series_name', 'Unknown'),
            "catalog_id": raw_data.get('catalog_id', ''),
            "series_code": raw_data.get('series_code', ''),
            "default_paint_code": raw_data.get('default_paint', ''),
            "official_url": f"https://www.ford.co.uk/cars/{raw_data.get('car_series_name', '').lower()}"
        }
    
    def optimize_vehicle_list(self, car_objects):
        """优化车型列表"""
        optimized_vehicles = []
        
        for i, car_obj in enumerate(car_objects, 1):
            optimized_vehicle = {
                "id": i,
                "basic_info": {
                    "model_name": car_obj.get('model_name', 'Unknown'),
                    "starting_price": car_obj.get('price', 'N/A'),
                    "primary_drive": car_obj.get('drive', 'Unknown')
                },
                "powertrain": {
                    "available_drives": self.optimize_drive_types(car_obj.get('drive_types', [])),
                    "primary_drive_details": self.extract_drive_details(car_obj.get('drive', ''))
                },
                "body_styles": self.optimize_body_styles(car_obj.get('body_styles', [])),
                "exterior": {
                    "available_colors": self.optimize_colors(car_obj.get('colors', [])),
                    "total_color_options": len(car_obj.get('colors', []))
                },
                "interior": {
                    "available_options": car_obj.get('interiors', []),
                    "total_interior_options": len(car_obj.get('interiors', []))
                },
                "optional_equipment": {
                    "extras": self.optimize_extras(car_obj.get('extras', [])),
                    "total_extras": len(car_obj.get('extras', []))
                },
                "standard_features": {
                    "key_features": car_obj.get('key_features', []),
                    "total_features": len(car_obj.get('key_features', []))
                },
                "specifications": car_obj.get('specifications', {}),
                "configuration_id": self.generate_configuration_id(car_obj)
            }
            
            optimized_vehicles.append(optimized_vehicle)
        
        return optimized_vehicles
    
    def optimize_drive_types(self, drive_types):
        """优化驱动类型信息"""
        optimized_drives = []
        
        for drive in drive_types:
            optimized_drive = {
                "name": drive.get('name', ''),
                "price_modifier": drive.get('price', 'Standard'),
                "description": drive.get('description', ''),
                "engine_info": self.extract_engine_info(drive.get('name', '')),
                "transmission_info": self.extract_transmission_info(drive.get('name', '')),
                "drivetrain": self.extract_drivetrain_info(drive.get('name', ''))
            }
            optimized_drives.append(optimized_drive)
        
        return optimized_drives
    
    def optimize_body_styles(self, body_styles):
        """优化车身样式信息"""
        optimized_styles = []
        
        for style in body_styles:
            optimized_style = {
                "name": style.get('name', ''),
                "price_modifier": style.get('price', 'Standard'),
                "associated_drive": style.get('associated_drive', ''),
                "description": style.get('description', ''),
                "category": self.categorize_body_style(style.get('name', ''))
            }
            optimized_styles.append(optimized_style)
        
        return optimized_styles
    
    def optimize_colors(self, colors):
        """优化颜色信息"""
        optimized_colors = []
        
        for color in colors:
            if isinstance(color, str):
                optimized_color = {
                    "name": color,
                    "price_modifier": "Standard",
                    "type": self.classify_color_type(color)
                }
            else:
                optimized_color = {
                    "name": color.get('name', ''),
                    "price_modifier": color.get('price', 'Standard'),
                    "color_code": color.get('colour_code', ''),
                    "type": self.classify_color_type(color.get('name', ''))
                }
            
            optimized_colors.append(optimized_color)
        
        return optimized_colors
    
    def optimize_extras(self, extras):
        """优化选装件信息"""
        optimized_extras = []
        
        # 按类别分组
        categories = {}
        
        for extra in extras:
            extra_name = extra.get('Extra_name', '')
            extra_price = extra.get('price', 'Optional')
            
            category = self.categorize_extra(extra_name)
            
            if category not in categories:
                categories[category] = []
            
            categories[category].append({
                "name": extra_name,
                "price": extra_price,
                "description": self.generate_extra_description(extra_name)
            })
        
        # 转换为有序列表
        for category, items in categories.items():
            optimized_extras.append({
                "category": category,
                "items": items,
                "count": len(items)
            })
        
        return optimized_extras
    
    def extract_drive_details(self, drive_str):
        """从驱动字符串中提取详细信息"""
        details = {
            "engine": "Unknown",
            "power": "Unknown", 
            "transmission": "Unknown",
            "drivetrain": "Unknown"
        }
        
        if not drive_str:
            return details
        
        # 提取发动机信息
        engine_match = re.search(r'(\d+\.?\d*L?\s*EcoBoost)', drive_str)
        if engine_match:
            details["engine"] = engine_match.group(1)
        
        # 提取功率信息
        power_match = re.search(r'(\d+PS)', drive_str)
        if power_match:
            details["power"] = power_match.group(1)
        
        # 提取变速箱信息
        if 'Manual' in drive_str:
            details["transmission"] = "Manual"
        elif 'Automatic' in drive_str or 'PowerShift' in drive_str:
            details["transmission"] = "Automatic"
        
        # 提取驱动方式
        if 'FWD' in drive_str:
            details["drivetrain"] = "Front Wheel Drive"
        elif 'AWD' in drive_str:
            details["drivetrain"] = "All Wheel Drive"
        elif 'RWD' in drive_str:
            details["drivetrain"] = "Rear Wheel Drive"
        
        return details
    
    def extract_engine_info(self, drive_str):
        """提取发动机信息"""
        import re
        engine_match = re.search(r'(\d+\.?\d*L?\s*\w*)', drive_str)
        return engine_match.group(1) if engine_match else "Unknown"
    
    def extract_transmission_info(self, drive_str):
        """提取变速箱信息"""
        if 'Manual' in drive_str:
            return "Manual"
        elif 'Automatic' in drive_str or 'PowerShift' in drive_str:
            return "Automatic" 
        return "Unknown"
    
    def extract_drivetrain_info(self, drive_str):
        """提取驱动方式信息"""
        if 'FWD' in drive_str:
            return "Front Wheel Drive"
        elif 'AWD' in drive_str:
            return "All Wheel Drive"
        elif 'RWD' in drive_str:
            return "Rear Wheel Drive"
        return "Unknown"
    
    def categorize_body_style(self, style_name):
        """分类车身样式"""
        style_lower = style_name.lower()
        
        if 'hatchback' in style_lower:
            return "Hatchback"
        elif 'estate' in style_lower or 'wagon' in style_lower:
            return "Estate/Wagon"
        elif 'sedan' in style_lower or 'saloon' in style_lower:
            return "Sedan"
        elif 'suv' in style_lower:
            return "SUV"
        elif 'coupe' in style_lower:
            return "Coupe"
        else:
            return "Other"
    
    def classify_color_type(self, color_name):
        """分类颜色类型"""
        if not color_name:
            return "Unknown"
        
        color_lower = color_name.lower()
        
        if 'metallic' in color_lower:
            return "Metallic"
        elif 'pearl' in color_lower or 'pearlescent' in color_lower:
            return "Pearl"
        elif 'matte' in color_lower or 'matt' in color_lower:
            return "Matte"
        else:
            return "Solid"
    
    def categorize_extra(self, extra_name):
        """分类选装件"""
        name_lower = extra_name.lower()
        
        if any(word in name_lower for word in ['safety', 'assist', 'brake', 'sensor', 'camera', 'blind spot']):
            return "Safety & Driver Assistance"
        elif any(word in name_lower for word in ['audio', 'sound', 'music', 'radio', 'entertainment', 'sync']):
            return "Entertainment & Technology"
        elif any(word in name_lower for word in ['seat', 'heated', 'comfort', 'climate', 'air']):
            return "Comfort & Convenience"
        elif any(word in name_lower for word in ['wheel', 'alloy', 'tire', 'rim']):
            return "Wheels & Styling"
        elif any(word in name_lower for word in ['roof', 'sunroof', 'panorama']):
            return "Roof & Exterior"
        elif any(word in name_lower for word in ['pack', 'package']):
            return "Option Packages"
        else:
            return "Other Options"
    
    def generate_extra_description(self, extra_name):
        """生成选装件描述"""
        # 这里可以根据选装件名称生成更详细的描述
        return f"Optional equipment: {extra_name}"
    
    def generate_configuration_id(self, car_obj):
        """生成配置ID"""
        model = car_obj.get('model_name', 'Unknown')
        drive = car_obj.get('drive', 'Unknown')
        
        # 简化ID生成逻辑
        config_id = f"{model}_{hash(drive) % 10000}"
        return config_id
    
    def create_summary_section(self, raw_data):
        """创建汇总部分"""
        car_objects = raw_data.get('car_objects', [])
        
        total_drives = sum(len(car.get('drive_types', [])) for car in car_objects)
        total_body_styles = sum(len(car.get('body_styles', [])) for car in car_objects)
        total_colors = sum(len(car.get('colors', [])) for car in car_objects)
        total_interiors = sum(len(car.get('interiors', [])) for car in car_objects)
        total_extras = sum(len(car.get('extras', [])) for car in car_objects)
        total_features = sum(len(car.get('key_features', [])) for car in car_objects)
        
        return {
            "total_vehicles": len(car_objects),
            "configuration_options": {
                "drive_types": total_drives,
                "body_styles": total_body_styles,
                "exterior_colors": total_colors,
                "interior_options": total_interiors,
                "optional_equipment": total_extras,
                "standard_features": total_features
            },
            "data_quality": {
                "completeness_score": self.calculate_completeness_score(car_objects),
                "last_updated": datetime.now().isoformat()
            }
        }
    
    def calculate_completeness_score(self, car_objects):
        """计算数据完整性评分"""
        if not car_objects:
            return 0.0
        
        total_score = 0.0
        required_fields = ['model_name', 'price', 'drive', 'colors', 'interiors', 'extras', 'key_features']
        
        for car_obj in car_objects:
            car_score = 0.0
            
            for field in required_fields:
                if field in car_obj and car_obj[field]:
                    if isinstance(car_obj[field], list):
                        car_score += 1.0 if len(car_obj[field]) > 0 else 0.5
                    else:
                        car_score += 1.0
                else:
                    car_score += 0.0
            
            total_score += car_score / len(required_fields)
        
        return round(total_score / len(car_objects), 2)
    
    def generate_optimization_stats(self, raw_data, optimized_data):
        """生成优化统计信息"""
        raw_size = len(json.dumps(raw_data, ensure_ascii=False))
        optimized_size = len(json.dumps(optimized_data, ensure_ascii=False))
        
        self.optimization_stats = {
            "original_size": raw_size,
            "optimized_size": optimized_size,
            "size_difference": optimized_size - raw_size,
            "structure_improvements": [
                "添加了元数据部分",
                "重新组织了车型数据结构",
                "分类整理了选装件",
                "添加了数据汇总信息",
                "改进了字段命名和层级"
            ]
        }
        
        print(f"📊 优化统计:")
        print(f"  原始大小: {raw_size:,} 字符")
        print(f"  优化后大小: {optimized_size:,} 字符") 
        print(f"  大小变化: {optimized_size - raw_size:+,} 字符")
        print(f"  结构改进: {len(self.optimization_stats['structure_improvements'])} 项")


def main():
    """主函数"""
    print("🎯 福特配置器输出格式优化")
    print("=" * 50)
    
    optimizer = OutputFormatOptimizer()
    
    # 输入输出文件路径
    input_file = './release/output.json'
    output_file = './release/optimized_output.json'
    
    # 执行优化
    if optimizer.optimize_output_file(input_file, output_file):
        print("\n🎉 输出格式优化完成！")
        print(f"📁 优化后的文件: {output_file}")
        
        # 显示统计信息
        if optimizer.optimization_stats:
            stats = optimizer.optimization_stats
            print(f"\n📈 优化效果:")
            for improvement in stats['structure_improvements']:
                print(f"  ✅ {improvement}")
        
        return True
    else:
        print("\n❌ 输出格式优化失败")
        return False


if __name__ == "__main__":
    import re
    main()